<?php
/**
 * 
 */
class Pidguin_Session_SaveHandler_DbTable extends Zend_Session_SaveHandler_DbTable
{	
	/**
	 * Object client
	 *
	 * @var object Client
	 */
	protected $_client = null;
	
	protected $_userId = null;
	
	public function __construct($config)
	{
		$this->_client = Pidguin_Client::getInstance();
		parent::__construct($config);
	}
	
	public function setUserId($id)
	{
		$this->_userId = $id;
	}
	
	public function getUserId()
	{		
		return $this->_userId;
	}
	
	/**
     * Write session data
     *
     * @param string $id
     * @param string $data
     * @return boolean
     */
    public function write($id, $data)
    {
        $return = false;
        $data = array(
					  'ip' => $this->_client->getClientIp(),
					  'browser' => $this->_client->getClientBrowserName(),
					  'device_type' => $this->_client->getDeviceType(),
					  $this->_modifiedColumn => time(),
                      $this->_dataColumn     => (string) $data);

        $rows = call_user_func_array(array(&$this, 'find'), $this->_getPrimary($id));

        if (count($rows)) {
            $data[$this->_lifetimeColumn] = $this->_getLifetime($rows->current());

            if ($this->update($data, $this->_getPrimary($id, self::PRIMARY_TYPE_WHERECLAUSE))) {
                $return = true;
            }
        } else {
            $data[$this->_lifetimeColumn] = $this->_lifetime;

            if ($this->insert(array_merge($this->_getPrimary($id, self::PRIMARY_TYPE_ASSOC), $data))) {
                $return = true;
            }
        }

        return $return;
    }
}
?>
